<script setup lang="ts">
import { ElTable, ElTableColumn, ElPagination, ElButton, vLoading, ElIcon, ElTooltip, ElSelectV2, ElInput } from "element-plus"
import Nifi from "../../nifi";
import { computed, h, reactive, ref, toRef, watch } from "vue";
import { chunk } from "lodash-es";
//
import StartElem from "./start.vue"
import StopElem from "./stop.vue"
import NewElem from "./new.vue"
// @ts-ignore
import ConfigElem from "./config.vue"

import {t} from "../../i18n/index"

interface Props {
    nifi: Nifi
    groupId: string
    id?: string
}
//
const emits = defineEmits<{ addGroup: [groupId: string, id: string] ,close:[]}>()
const props = defineProps<Props>();
const { nifi, groupId } = props;
const id = toRef(props, 'id')

//
const isDisabled = computed(() => nifi.graph.mode.value == 'prod')
const groupOptions = Object.keys(nifi.group.breadcrumb).map(id => ({ label: nifi.group.breadcrumb[id].name, value: id }))
const statusOption = ["DISABLED", "ENABLED", "VALIDATING", "DISABLING", "ENABLING"].map(n => ({ label: n, value: n }))
//
const pages = reactive({ pageNum: 1, pageSize: 10, total: 0, sizes: [], layout: "prev, pager, next, total" })
const search = ref(id.value || '')
const status = ref<string[]>([])
const group = ref<string[]>([])
//
const list = reactive<any[]>([])
const flist = computed(() => {
    let l = list;
    if (l.length == 0) { return l }
    if (search.value) {
        l = l.filter(d => d.id == search.value || d.component.name.toLowerCase().includes(search.value.toLowerCase()))
    }
    if (status.value.length > 0) {
        l = l.filter(d => status.value.includes(d.status.runStatus))
    }
    if (group.value.length > 0) {
        l = l.filter(d => group.value.includes(d.parentGroupId))
    }
    pages.total = l.length;
    return l;
})
const plist = computed(() => {
    const l = flist.value;
    return chunk(l, pages.pageSize)
})
const data = computed(() => plist.value[pages.pageNum - 1] || [])
const loading = ref(false)
//
const refresh = async () => {
    loading.value = true;
    const res = await nifi.ControlService.get(groupId);
    list.length = 0;
    list.push(...res)
    loading.value = false;
}

// 初始化
refresh();
//
const tableRef = ref();
watch(id, (v) => {
    if (v) {
        clearQuery();
        search.value = v;
    }
})
//
const clearQuery = () => {
    search.value = "";
    status.value = [];
    group.value = [];
}
//
const handleRefresh = () => { refresh() };

const handleAdd = () => {
    nifi.box.dialog((box) => h(NewElem, {
        nifi, groupId, onFinish: (b) => {
            if (b != false) {
                box.close();
                refresh();
                if (typeof b === 'string') {
                    search.value = b;
                }
            }
        }
    }), { showFooter: false })
}

const handleReset = () => {
    clearQuery()
}

const handleConfig = (row: any) => {
    nifi.box.dialog((box) => h(ConfigElem, {
        nifi, id: row.id, onFinish: (bool: boolean) => {
            if (bool) {
                refresh();
            }
            box.close();
        }, onGoTo: (d: any) => {
            const id = d.component.id;
            const referenceType = d.component.referenceType;
            if (referenceType == 'ControllerService') {
                nifi.ControlService.detail(id).then((res) => {
                    const groupId = res.parentGroupId;
                    emits('addGroup', groupId, id)
                })
            }
            else if (referenceType == 'Processor') {
                const groupId = d.component.groupId;
                nifi.group.goToCell(groupId,id);
                // nifi.Graph.goToCell(groupId,id)
                emits('close')
            }
            box.close();
        }
    }), { showFooter: false })
}
const handleGo = (row: any) => {
    emits('addGroup', row.parentGroupId, row.id)
}
// 启用控制器服务
const handleEnableCS = (row: any) => {

    nifi.box.dialog((box) => h(StartElem, {
        nifi, id: row.id, onlyService: true, onFinish: (b) => {
            if (b) {
                box.close();
                refresh();
            }
        }
    }), { showFooter: false })
}
// 启用控制器服务和引用服务
const handleEnableAll = (row: any) => {
    nifi.box.dialog((box) => h(StartElem, {
        nifi, id: row.id, onlyService: false, onFinish: (b) => {
            if (b) {
                box.close();
                refresh();
            }
        }
    }), { showFooter: false })
}
//
const handleDisable = (row: any) => {
    nifi.box.dialog((box) => h(StopElem, {
        nifi, id: row.id, onFinish: (b) => {
            if (b) {
                box.close();
                refresh();
            }
        }
    }), { showFooter: false })
}

const handleDelete = async (row: any) => {
    await nifi.ControlService.remove(row);
    refresh();
}
//

</script>


<template>
    <div class="w-full h-full flex flex-col gap-8px">
        <!-- header -->
        <div class="h-40px flex items-center justify-between gap-10px">
            <div>
                <ElButton type="success" :loading="loading" @click="handleRefresh">{{t('cs-list-refresh')}}</ElButton>
                <ElButton v-if="!isDisabled" :loading="loading" type="primary" @click="handleAdd">{{t('cs-list-new')}}
                </ElButton>
            </div>
            <div class="flex items-center gap-10px">
                <ElSelectV2 class="important-w-200px" v-model="group" multiple collapse-tags :placeholder="t('cs-list-group-placeholder')"
                    :options="groupOptions" :teleported="false" ></ElSelectV2>
                <ElSelectV2 class="important-w-200px" v-model="status" multiple collapse-tags :placeholder="t('cs-list-status-placeholder')"
                    :options="statusOption" :teleported="false" ></ElSelectV2>
                <ElInput class="important-w-200px" :placeholder="t('cs-list-search-placeholder')" v-model="search" clearable></ElInput>
                <ElButton @click="handleReset" :loading="loading">{{t('cs-list-reset')}}</ElButton>
            </div>
        </div>
        <div class="flex-1 overflow-hidden">
            <ElTable ref="tableRef" class="important-h-full" v-loading="loading" :data="data" stripe highlight-current-row
                row-key="id">
                <ElTableColumn :label="t('cs-list-table-index')" width="80" align="center" fixed >
                    <template #default="{ $index }">{{ pages.pageSize * (pages.pageNum - 1) + $index + 1 }}</template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-list-table-name')" prop="component.name" min-width="120" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn :label="t('cs-list-table-type')" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.component.type.split('.').pop() }} {{ row.component.bundle.version }}
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-list-table-group')" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ row.component.bundle.group }} {{ row.component.bundle.artifact }}
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-list-table-status')" width="120" show-overflow-tooltip>
                    <template #default="{ row }">
                        <ElIcon v-if="row.component.validationStatus != 'INVALID'"
                            :class="['', { 'is-loading': /ING$/.test(row?.status?.runStatus) || row.status.validationStatus == 'VALIDATING' }]">
                            <i v-if="row.status.validationStatus == 'VALID' && row.status.runStatus == 'DISABLED'"
                                class="i-ic:round-flash-off w-1em h-1em c-#909399"></i>
                            <i v-if="row.status.validationStatus == 'VALID' && row.status.runStatus == 'ENABLED'"
                                class="i-line-md:play-twotone w-1em h-1em c-#67C23A"></i>

                            <!-- <i class="i-fluent-color:warning-16 w-1em h-1em"
                                v-if="row.status.validationStatus == 'INVALID'"></i> -->
                            <i v-if="row.status.validationStatus == 'VALIDATING'"
                                class="i-line-md:loading-alt-loop w-1em h-1em c-#909399"></i>
                            <i v-if="row.status.runStatus == 'DISABLING'"
                                class="i-line-md:loading-alt-loop w-1em h-1em c-#E6A23C"></i>
                            <i v-if="row.status.validationStatus == 'VALID' && row.status.runStatus == 'ENABLING'"
                                class="i-line-md:loading-alt-loop w-1em h-1em c-#409EFF"></i>
                        </ElIcon>
                        <ElTooltip v-if="row.component.validationStatus == 'INVALID'" placement="top-start"
                            :content="row.component.validationErrors?.map((v: any) => `<p class=':uno: c-#999 fw-bold'>${v}</p>`).join(' ')"
                            raw-content effect="light">
                            <ElIcon class="c-#E6A23C">
                                <i class="i-fluent-color:warning-16 w-1em h-1em"></i>
                            </ElIcon>
                        </ElTooltip>
                        <span class="lh-1em m-l-.5em">{{ row.status.validationStatus == 'VALID' ? row.status.runStatus :
                            row.status.validationStatus }}</span>
                    </template>
                </ElTableColumn>
                <ElTableColumn :label="t('cs-list-table-parent-group')" width="120" show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ nifi.group.breadcrumb[row.parentGroupId]?.name || '' }}
                    </template>
                </ElTableColumn>
                <ElTableColumn width="140" :label="t('cs-list-table-operate')" fixed="right">

                    <template #default="{ row }">
                        <ElButton v-if="row.parentGroupId != groupId" :title="t('cs-list-table-operate-goto')" @click="() => handleGo(row)" link
                            type="success">
                            <div class="i-fa6-solid:right-long w-1em h-1em"></div>
                        </ElButton>
                        <template v-else>
                            <ElButton :title="t('cs-list-table-operate-config')" @click="() => handleConfig(row)" link type="primary">
                                <div class="i-solar:settings-outline w-1em h-1em"></div>
                            </ElButton>
                            <ElButton v-if="row.status.runStatus == 'ENABLING' || row.status.runStatus == 'ENABLED'"
                                :disabled="isDisabled" :title="t('cs-list-table-operate-disable')" @click="() => handleDisable(row)" link type="warning">
                                <div class="i-ic:round-flash-off w-1em h-1em c-#909399"></div>
                            </ElButton>
                            <ElButton
                                v-if="row.status.validationStatus == 'VALID' && row.status.runStatus == 'DISABLED'"
                                :disabled="isDisabled" :title="t('cs-list-table-operate-enable')" @click="() => handleEnableCS(row)" link
                                type="primary">
                                <div class="i-ion:flash-outline w-1em h-1em"></div>
                            </ElButton>
                            <ElButton
                                v-if="row.status.validationStatus == 'VALID' && row.status.runStatus == 'DISABLED'"
                                :disabled="isDisabled" :title="t('cs-list-table-operate-enables')" @click="() => handleEnableAll(row)" link
                                type="primary">
                                <div class="i-fluent-mdl2:flash-auto w-1em h-1em"></div>
                            </ElButton>
                            <ElButton v-if="row.status.runStatus == 'DISABLED'" :disabled="isDisabled" :title="t('cs-list-table-operate-delete')"
                                @click="() => handleDelete(row)" link type="danger">
                                <div class="i-pajamas:remove w-1em h-1em"></div>
                            </ElButton>
                        </template>
                    </template>
                </ElTableColumn>
            </ElTable>
        </div>

        <div class="h-40px flex justify-end items-end">
            <ElPagination v-model:current-page="pages.pageNum" v-model:page-size="pages.pageSize" :total="pages.total"
                :page-sizes="pages.sizes" :layout="pages.layout"></ElPagination>
        </div>

    </div>
</template>